package com.example.weixinredpackokhttp.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.example.weixinredpackokhttp.model.RedPackEvent;
import com.example.weixinredpackokhttp.utils.EventBusUtil;
import com.example.weixinredpackokhttp.utils.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * @author shadow
 */
@Service
public class RedPackServiceImpl implements RedPackService{

    /**
     * 红包已经领取过
     */
    public static final String REDPACK_REDIS_LUA_RES_CODE_ACQUIRED = "0";
    /**
     * 红包已经领取完
     */
    public static final String REDPACK_REDIS_LUA_RES_CODE_EMPTY = "-1";

    @Autowired
    private DefaultRedisScript<String> redisScript;
    @Autowired
    private RedisOperator redisOperator;

    @Override
    public String send(String openId) {

        // 并发控制, 抽取Redis里面预加载好的红包
        Object eval = redisOperator.execute(redisScript, Collections.singletonList(openId));
        if (eval == null) {
            return "你没有抽中红包哦";
        }
        if (!JSONUtil.isJson(eval.toString())) {
            // 用户已领取红包
            if (REDPACK_REDIS_LUA_RES_CODE_ACQUIRED.equals(eval.toString())) {
                return "您已经领取过红包啦";
            }
            // 红包已发完
            if (REDPACK_REDIS_LUA_RES_CODE_EMPTY.equals(eval.toString())) {
                return "红包已经抽完啦";
            }
        }
        StaticLog.info("[{}]抽红包结果:{}", openId, eval.toString());
        JSONObject json = JSONUtil.parseObj(eval.toString());
        String money = json.getStr("money");
        // 发送事件给eventbus, 处理事件在这个方法 RedPackListener.java
        EventBusUtil.asyncPost(new RedPackEvent(openId, money));

        return money;
    }
}
